/**
 * 保存当前滚动的位置，刷新页面时回到上次位置
 * @param element dom元素
 * @param key 唯一key
 * @param config 配置 （store和滚动
 * @returns
 */
export const useStorageScroll = (
  element: Ref<HTMLElement | SVGElement | Window | undefined | null>,
  key: string,
  config?: {
    behavior?: 'auto' | 'smooth'
    storage?: 'localStorage' | 'sessionStorage'
  },
) => {
  const { behavior = 'smooth', storage = 'localStorage' } = config || {}

  const scrollPosition = useStorage(key, { top: 0, left: 0 }, window[storage])

  function scrollEvent(e: Event) {
    const dom = e.target as HTMLElement
    const { scrollTop: top, scrollLeft: left } = dom
    scrollPosition.value = { top, left }
  }

  onMounted(() => {
    element.value?.scrollTo({
      ...scrollPosition.value,
      behavior,
    })
    element.value?.addEventListener('scroll', scrollEvent)
  })

  onUnmounted(() => {
    element.value?.removeEventListener('scroll', scrollEvent)
  })

  return scrollPosition
}
